package com.yyx.oneselfnetty.common;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class StartServer {

    public static void main(String[] args) {
        new ServerBootstrap() //1.启动器，负责组装netty组件，启动服务器
                .group(new NioEventLoopGroup()) //2.BossEventLoop, WorkEventLoop (selector, thread),group组
                .channel(NioServerSocketChannel.class) //3.选择服务器的serverSocketChannel实现
                //4.boss负责处理连接，woker（child）负责处理读写
                // 5.channel代表和客户端进行数据读写的通道，Initializer负责初始化NioSocketChannel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 添加具体handler
                        ch.pipeline().addLast(new StringDecoder()); // 将bytedbuf转化为字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){ //处理器适配器
                            @Override
                            //读事件
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
                                System.out.println(msg);
                            }
                        });
                    }
                }).bind(8080);//6.绑定监听接口
    }
}
